import { Injectable, Logger } from '@nestjs/common';
import axios from 'axios';
import * as cheerio from 'cheerio';
import xlsx from 'node-xlsx';
import * as fs from 'fs';
import * as path from 'path';
import { resolve } from 'path';

const excelPath = path.resolve(__dirname, '../', '茅台净利润.xlsx');
@Injectable()
export class AppService {
  private readonly logger = new Logger(AppService.name);
  constructor() {
    this.exctor();
  }

  async exctor() {
    this.logger.verbose('开始读取页面，生成数据...');

    const [titleList, dataList] = await this.getData();

    this.logger.verbose('读取页面，生成数据成功');

    this.logger.verbose('开始生成 excel buffer...');

    const result = await this.exportExcel(titleList, dataList);

    this.logger.verbose('生成 excel buffer 成功');

    this.logger.verbose('开始写入文件...');

    const end = await this.writeExcel(excelPath, result);

    if (end) {
      this.logger.verbose('写入文件成功');
    }
  }

  async getData() {
    const url = 'http://quotes.money.163.com/f10/zycwzb_600519.html';
    const res = await axios.get(url);
    const $ = cheerio.load(res.data);

    const titleList = [];
    const dataList = [];
    $('.scr_table .dbrow th').each((_, ele) => {
      titleList.push($(ele).text());
    });

    $('.scr_table tr')
      .eq(11)
      .find('td')
      .each((_, ele) => {
        dataList.push($(ele).text());
      });

    titleList.unshift('报告日期');
    dataList.unshift('净利润(扣除非经常性损益后)(万元)');

    return [titleList, dataList];
  }

  async exportExcel(titleList, dataList, xlsName = 'sheet1') {
    const data = [titleList, ...[dataList]];
    const buffer = xlsx.build([
      {
        name: xlsName,
        data,
      },
    ]);

    return buffer;
  }

  async writeExcel(path, data) {
    return new Promise<boolean>((resolve) => {
      fs.writeFile(path, data, (err) => {
        if (err) throw err;
        resolve(true);
      });
    });
  }
}
